package ui.activity;


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.avchat.AVChatCallback;
import com.netease.nimlib.sdk.avchat.AVChatManager;
import com.netease.nimlib.sdk.avchat.AVChatStateObserverLite;
import com.netease.nimlib.sdk.avchat.constant.AVChatChannelProfile;
import com.netease.nimlib.sdk.avchat.constant.AVChatType;
import com.netease.nimlib.sdk.avchat.constant.AVChatUserRole;
import com.netease.nimlib.sdk.avchat.model.AVChatAudioFrame;
import com.netease.nimlib.sdk.avchat.model.AVChatChannelInfo;
import com.netease.nimlib.sdk.avchat.model.AVChatControlEvent;
import com.netease.nimlib.sdk.avchat.model.AVChatData;
import com.netease.nimlib.sdk.avchat.model.AVChatNetworkStats;
import com.netease.nimlib.sdk.avchat.model.AVChatParameters;
import com.netease.nimlib.sdk.avchat.model.AVChatSessionStats;
import com.netease.nimlib.sdk.avchat.model.AVChatVideoFrame;
import com.netease.nimlib.sdk.chatroom.ChatRoomMessageBuilder;
import com.netease.nimlib.sdk.chatroom.ChatRoomService;
import com.netease.nimlib.sdk.chatroom.ChatRoomServiceObserver;
import com.netease.nimlib.sdk.chatroom.constant.MemberQueryType;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomInfo;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMember;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMessage;
import com.netease.nimlib.sdk.chatroom.model.CustomChatRoomMessageConfig;
import com.netease.nimlib.sdk.chatroom.model.EnterChatRoomData;
import com.netease.nimlib.sdk.chatroom.model.EnterChatRoomResultData;
import com.netease.nimlib.sdk.document.DocumentManager;
import com.netease.nimlib.sdk.document.model.DMData;
import com.netease.nimlib.sdk.document.model.DMDocTransQuality;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.model.CustomNotification;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.nos.NosService;
import com.netease.nimlib.sdk.rts.RTSCallback;
import com.netease.nimlib.sdk.rts.RTSChannelStateObserver;
import com.netease.nimlib.sdk.rts.RTSManager2;
import com.netease.nimlib.sdk.rts.constant.RTSTunnelType;
import com.netease.nimlib.sdk.rts.model.RTSControlEvent;
import com.netease.nimlib.sdk.rts.model.RTSData;
import com.netease.nimlib.sdk.rts.model.RTSTunData;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapter.IMMessageAdapter;
import adapter.IMRoomMeberAdapter;
import base.BaseBean;
import base.activity.BaseNetActivity;
import bean.ChatRoomMemberBean;
import hollowsoft.slidingdrawer.SlidingDrawer;
import model.Document;
import model.FileDownloadStatusEnum;
import student.andlei.com.student.R;
import utils.DateUtils;
import utils.DensityUtil;
import utils.FloatWindowsService;
import utils.GlideUtils;
import utils.GsonUtils;
import utils.Logger;
import utils.QiniuUploadUtils;
import utils.SPUtils;
import utils.StringUtils;
import utils.log.LogUtil;
import utils.storage.StorageType;
import utils.storage.StorageUtil;
import view.CircleImageView;
import view.LiveSelectPenPopWindow;
import view.doodle.ActionTypeEnum;
import view.doodle.DoodleView;
import view.doodle.SupportActionType;
import view.doodle.Transaction;
import view.doodle.TransactionCenter;
import view.doodle.action.MyPath;
import view.listview.MeetingOptCommand;
import view.listview.MsgHelper;
import view.sdk.LivePlayer;
import view.sdk.model.MediaInfo;
import view.sdk.view.AdvanceSurfaceView;

import static com.netease.nimlib.sdk.avchat.constant.AVChatControlCommand.NOTIFY_VIDEO_OFF;
import static com.netease.nimlib.sdk.avchat.constant.AVChatControlCommand.NOTIFY_VIDEO_ON;
import static com.netease.nimlib.sdk.avchat.constant.AVChatControlCommand.SWITCH_AUDIO_TO_VIDEO;
import static com.netease.nimlib.sdk.avchat.constant.AVChatControlCommand.SWITCH_AUDIO_TO_VIDEO_AGREE;
import static com.netease.nimlib.sdk.avchat.constant.AVChatControlCommand.SWITCH_AUDIO_TO_VIDEO_REJECT;
import static com.netease.nimlib.sdk.avchat.constant.AVChatControlCommand.SWITCH_VIDEO_TO_AUDIO;


public class LiveBroadcastActivity extends BaseNetActivity implements DoodleView.FlipListener {
    private String TAG = "LiveBroadcastActivity";
    private static final int PERMISSION_REQUEST_CODE = 10;
    private Fragment MessageRoomfragment;
    private MediaProjectionManager mMediaProjectionManager;
    private RecyclerView recyclerView;
    private SearchView searchView;
    private ChatRoomMemberBean memberBean;
    private String sendType = "";
    //private List<ChatRoomMember> list_meber = new ArrayList<>();
    private List<ChatRoomMemberBean.mlist> alllist_meber = new ArrayList<>();
    private List<ChatRoomMessage> list_message = new ArrayList<>();
    private IMRoomMeberAdapter meberAdapter;
    private IMMessageAdapter messageAdapter;
    private TextView tv_onlinePeople;
    private RadioButton rb_taolun;
    private LinearLayout layout_edtext;
    private EditText ed_text_message;
    private Button bt_send;
    private TextView tv_suoping;//锁屏显示
    private boolean setSuoPing;
    private TextView tv_name,
            tv_screenshot,
            tv_all_onlinepeople ;
    private CheckBox   tv_mike,
            tv_raisehands,
            tv_notebook;
    private ImageView   tv_paint,
            tv_rubber,
            tv_clear;
    private String allOnline;
    private View layoutview;
    private CircleImageView iv_meitupian;
//    private
    /**
     * 直播信息
     */
    private LivePlayer player;
    private MediaInfo mediaInfo;
    private boolean mHardware = true;
    protected boolean isPauseInBackgroud;
    private String mVideoPath = "rtmp://v0e99f8ea.live.126.net/live/2cd333728c0647208dd64ad134a60079"; //文件路径
    private AdvanceSurfaceView surfaceView;
    private boolean mBackPressed;
    /**
     * 聊天室基本信息
     */
    private String roomId;
    private ChatRoomInfo roomInfo;
    private DoodleView doodleView; // 画板
    private String sessionId = "1139"; // 白板sessionId
    private Document document;
    private boolean isFileMode = false; // 是否是文档模式
    private ImageView ivBack;
    private ImageView btOpen;
    private SlidingDrawer slidingDrawer;
    private boolean isFirstComing = true; // 主播是否首次进入房间
    @Override
    public void success(String action, final BaseBean baseBean) {
        if(baseBean.code == 200){
            if(action.equals("note/addNote")){
                toast("添加笔记成功");
            }else if(action.equals("personal/getScheduleMember")){
                alllist_meber.clear();
                meberAdapter.notifyDataSetChanged();
                memberBean = (ChatRoomMemberBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean,ChatRoomMemberBean.class);
                ChatRoomMemberBean.mlist mlist = new ChatRoomMemberBean.mlist();
                mlist.accid = memberBean.accid;
                mlist.head_image = memberBean.head_image;
                mlist.student_id = memberBean.teacher_id;
                mlist.student_name = memberBean.teacher_name;
                if(memberBean.list == null){return;}
                memberBean.list.add(0,mlist);
                alllist_meber.addAll(memberBean.list);
                meberAdapter.setNewData(alllist_meber);
                allOnline = memberBean.sum+"";
                GetImMemberList();
            }

           // tv_all_onlinepeople.setText(""+"/"+memberBean.sum);
        }else {
            toast(baseBean.msg);
        }
    }
    @Override
    public void error(String action, Throwable e) {
    }


    @Override
    protected int getLayoutId() {
        layoutview = View.inflate(context, R.layout.activity_service_agreement, null);
        return R.layout.activity_live_broadcast;
    }
    @Override
    protected void findViews() {
        //hideBottomUIMenu();
        tv_suoping = getView(R.id.tv_suoping);
        iv_meitupian = getView(R.id.iv_meitupian);
        GlideUtils.loadImageViewHeadphotoLoding(context, SPUtils.getInstance(context).getString("head_image"),iv_meitupian);
        surfaceView = getView(R.id.live_texture);
        searchView = getView(R.id.search_view);
        tv_all_onlinepeople = getView(R.id.tv_all_onlinepeople);
        tv_onlinePeople = getView(R.id.tv_onlinePeople);
        tv_onlinePeople.setBackgroundResource(R.color.homepage_titlefont);
        tv_onlinePeople.setTextColor(0xFFffffff);
        rb_taolun = getView(R.id.radio_taolun);
        layout_edtext = getView(R.id.layout_edtext);
        ed_text_message = getView(R.id.ed_input_messagge);
        bt_send = getView(R.id.bt_send);
        tv_name = getView(R.id.tv_name);
        tv_mike = getView(R.id.tv_mike);
        tv_raisehands = getView(R.id.tv_raisehands);
        tv_notebook = getView(R.id.tv_notebook);
        tv_screenshot = getView(R.id.tv_screenshot);
        tv_paint = getView(R.id.tv_paint);
        tv_rubber = getView(R.id.tv_rubber);
        tv_clear = getView(R.id.tv_clear);
        ivBack = getView(R.id.iv_back_live_broadcast);
        btOpen = getView(R.id.bt_open_drawer_live_broadcast);
        recyclerView = getView(R.id.rcly_);
        doodleView = getView(R.id.doodle_view);
        //开启白板
        doodleView.setEnableView(true);
        //initDoodleView("");
        slidingDrawer = getView(R.id.sl_slidingdrawer_live_broadcast);
        slidingDrawer.lock();
    }
    @Override
    protected void formatViews() {
        loadData();
        tv_onlinePeople.setOnClickListener(this);
        rb_taolun.setOnClickListener(this);
        tv_mike.setOnClickListener(this);
        bt_send.setOnClickListener(this);
        tv_raisehands.setOnClickListener(this);
        tv_notebook.setOnClickListener(this);
        tv_screenshot.setOnClickListener(this);
        tv_paint.setOnClickListener(this);
        tv_rubber.setOnClickListener(this);
        tv_clear.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        btOpen.setOnClickListener(this);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                //搜索按钮点击
                loadData();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if(StringUtils.isNull(newText)){
                    loadData();
                }
                return false;
            }
        });
        // CreatRoomId();
        doLogin();
        //接收数据观察者 register  true为注册，false为注销
        RTSManager2.getInstance().observeReceiveData(sessionId, receiveDataObserver, true);
        //监听互动白板状态通道观察者 register  true为注册，false为注销
        RTSManager2.getInstance().observeChannelState(sessionId, channelStateObserver, true);
        //监听发送指令状态通道观察者 register  true为注册，false为注销
        RTSManager2.getInstance().observeControlNotification(sessionId, controlObserver, true);
        // 监听通话过程中状态变化。
        AVChatManager.getInstance().observeAVChatState(register, true);
        /**
         * 注册/注销网络通话控制消息（音视频模式切换通知和其他用户自定义控制指令通知）
         */
        AVChatManager.getInstance().observeControlNotification(callControlObserver, true);
        NIMClient.getService(ChatRoomServiceObserver.class)
                .observeReceiveMessage(incomingChatRoomMsg, true);
        NIMClient.getService(MsgServiceObserve.class).observeCustomNotification(customNotification, true);

        final List<String> missed = AVChatManager.checkPermission(activity);
        if (missed.size() == 0) {
            Log.i("AVChatManager---->",""+true);
          //  return true;
        } else {
            requestWhiteboardPermissions(activity);
            Log.i("AVChatManager---->",""+false);
           // return false;
        }

//        initPlayer();
    }
    private void loadData(){
        Map<String,Object> map = new HashMap<>();
        map.put("room_id",roomId);
        map.put("name",searchView.getQuery().toString());
        post("personal/getScheduleMember",map,BaseBean.class,false);
    }
    private static void requestWhiteboardPermissions(final Activity context) {
        final List<String> missed = AVChatManager.checkPermission(context);
        List<String> showRationale = new ArrayList<>();
        for (String permission : missed) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(context, permission)) {
                showRationale.add(permission);
            }
        }

        if (showRationale.size() > 0) {
            new AlertDialog.Builder(context)
                    .setMessage("You need to allow some permission")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(context, missed.toArray(new String[missed.size()]),
                                    PERMISSION_REQUEST_CODE);
                        }
                    })
                    .setNegativeButton("Cancel", null)
                    .create()
                    .show();
        } else {
            ActivityCompat.requestPermissions(context, missed.toArray(new String[missed.size()]), PERMISSION_REQUEST_CODE);
        }
    }

    //创建多人白板
    private void CreatRoomId() {
        RTSManager2.getInstance().createSession(sessionId, "extra msg", new RTSCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {

                toast("创建房间成功！");
                Log.i("---->", "创建房间成功");
                JoinRoom();
                //  initDoodleView(SPUtils.getInstance(LiveBroadcastActivity.this).getString("accid"));

            }

            @Override
            public void onFailed(int code) {
                Log.i("---->", "创建房间失败");
            }

            @Override
            public void onException(Throwable exception) {


                Log.i("---->", "创建房间异常");
            }
        });
    }
    //登录云服务器
    public void doLogin() {
        // LoginInfo info = new LoginInfo("8853984344","a78911ab1e34689b0823666a73f4d0478f7fe872");
        LoginInfo info = new LoginInfo(SPUtils.getInstance(this).getString("accid"), SPUtils.getInstance(this).getString("token")); // config...
        base.util.log.LogUtil.audio("accid---->"+SPUtils.getInstance(this).getString("accid")+"token---->"+SPUtils.getInstance(this).getString("token"));
        //LogUtil.app("accid---->"+SPUtils.getInstance(this).getString("accid")+"token---->"+SPUtils.getInstance(this).getString("token"));
        RequestCallback<LoginInfo> callback =
                new RequestCallback<LoginInfo>() {
                    @Override
                    public void onSuccess(LoginInfo loginInfo) {
                        toast("登录成功");
                        //  CreatRoomId();
                        JoinRoom();
                        JoinImRoom();
                        CollectAvData();
                        JoinAvRoom();
                       // CreateAvRoomID();
                       // CreateAvRoomID();
                       // JoinAvRoom();
                    }

                    @Override
                    public void onFailed(int i) {
                        toast("登录失败");
                    }

                    @Override
                    public void onException(Throwable throwable) {
                        toast("登录异常");
                    }
                    // 可以在此保存LoginInfo到本地，下次启动APP做自动登录用
                };
        NIMClient.getService(AuthService.class).login(info)
                .setCallback(callback);
    }
    //加入多人白板房间
    private void JoinRoom() {
        boolean enableServerRecord = true;
        RTSManager2.getInstance().joinSession(sessionId, enableServerRecord, new RTSCallback<RTSData>() {
            @Override
            public void onSuccess(RTSData rtsData) {
                toast("加入多人白板成功");
                initDoodleView("");
            }

            @Override
            public void onFailed(int code) {
                toast("加入多人白板失败");
            }

            @Override
            public void onException(Throwable exception) {

            }
        });
    }
    //创建音视频房间
    private void CreateAvRoomID() {
        AVChatManager.getInstance().createRoom(sessionId, "", new AVChatCallback<AVChatChannelInfo>() {
            @Override
            public void onSuccess(AVChatChannelInfo avChatChannelInfo) {
                toast("创建音视频房间成功");
                CollectAvData();
                JoinAvRoom();
            }

            @Override
            public void onFailed(int i) {

            }

            @Override
            public void onException(Throwable throwable) {

            }
        });
    }
    //音视频数据采集
    private void  CollectAvData(){
        //开始视频采集
        AVChatManager.getInstance().enableRtc();
        AVChatParameters avChatParameters = new AVChatParameters();
        avChatParameters.setBoolean(AVChatParameters.KEY_AUDIO_HIGH_QUALITY, true);
        AVChatManager.getInstance().setChannelProfile(AVChatChannelProfile.CHANNEL_PROFILE_DEFAULT);
        AVChatManager.getInstance().setParameters(avChatParameters);
        //甚至身份（观众）
        AVChatManager.getInstance().setParameter(AVChatParameters.KEY_SESSION_MULTI_MODE_USER_ROLE, AVChatUserRole.AUDIENCE);
    }
    private String TeacherId;
    //加入音视频房间
    private void JoinAvRoom() {
        AVChatManager.getInstance().joinRoom2(sessionId, AVChatType.AUDIO, new AVChatCallback<AVChatData>() {
            @Override
            public void onSuccess(AVChatData avChatData) {
                toast("加入音视频房间成功");
                TeacherId  = avChatData.getExtra();
               // CollectAvData();
            }

            @Override
            public void onFailed(int i) {

            }

            @Override
            public void onException(Throwable throwable) {

            }
        });
    }
    //离开音视频房间
    private void leaveAvRoom(){
        //离开房间
        AVChatManager.getInstance().leaveRoom2(sessionId, new AVChatCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                toast("离开音视频房间成功");
            }
            @Override
            public void onFailed(int i) {

            }
            @Override
            public void onException(Throwable throwable) {

            }
        });
        //关闭音视频引擎
        AVChatManager.getInstance().disableRtc();
    }
    //改变音视频 用户身份
    private void ChangeUserCard(){
        //自己是否是观众
        if(AVChatManager.getInstance().isAudienceRole()){
            //离开观众身份
            MsgHelper.getInstance().sendP2PCustomNotification(sessionId,MeetingOptCommand.SPEAK_REQUEST.getValue(),TeacherId,null);
           // AVChatManager.getInstance().enableAudienceRole(false);
        }else {
            //加入观众身份
            MsgHelper.getInstance().sendP2PCustomNotification(sessionId,MeetingOptCommand.SPEAK_REQUEST_CANCEL.getValue(),TeacherId,null);
          //  AVChatManager.getInstance().enableAudienceRole(true);
        }

    }

    //离开互动白板通知
    private void onleave(String sessionId) {
        RTSManager2.getInstance().leaveSession(sessionId, new RTSCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                toast("离开互动白板成功");
            }

            @Override
            public void onFailed(int code) {
                toast("离开互动白板失败");
            }

            @Override
            public void onException(Throwable exception) {
                toast("离开互动白板异常");
            }
        });
    }
    //发送多人控制指令
    private void SendCtrlComend(String data) {
        //data      控制指令内容
        RTSManager2.getInstance().sendControlCommand(sessionId, data, new RTSCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {

            }

            @Override
            public void onFailed(int code) {

            }

            @Override
            public void onException(Throwable exception) {

            }
        });
    }
    @Override
    protected void formatData() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        meberAdapter = new IMRoomMeberAdapter(context,R.layout.item_im_meber,alllist_meber);
        recyclerView.setAdapter(meberAdapter);
        LinearLayoutManager mlayoutManager = new LinearLayoutManager(context);
        mlayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(mlayoutManager);
        messageAdapter = new IMMessageAdapter(R.layout.item_im_message,list_message);
    }
    @Override
    protected void getBundle(Bundle bundle) {
            sessionId = bundle.getString("chatroom_id");
            roomId = bundle.getString("room_id");
            tv_name.setText(SPUtils.getInstance(context).getString("name"));
    }
    private void initonlinePeopleandtaolun(){
        tv_onlinePeople.setBackgroundResource(R.color.appstyletitlecolor);
        tv_onlinePeople.setTextColor(0xFF333333);
        rb_taolun.setBackgroundResource(R.color.appstyletitlecolor);
        rb_taolun.setTextColor(0xFF333333);
    }
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint("WrongConstant")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //返回
            case R.id.iv_back_live_broadcast:
                if(setSuoPing){
                    toast("锁屏中，无法返回退出");
                    return;
                }
                finish();

                break;
            //弹出 或 关闭 侧滑栏
            case R.id.bt_open_drawer_live_broadcast:
                slidingDrawer.animateToggle();
                if (slidingDrawer.isOpened()) {
                    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(new RelativeLayout.LayoutParams(DensityUtil.dip2px(LiveBroadcastActivity.this, 55), RelativeLayout.LayoutParams.MATCH_PARENT));
                    slidingDrawer.setLayoutParams(layoutParams);
                } else {
                    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(new RelativeLayout.LayoutParams(DensityUtil.dip2px(LiveBroadcastActivity.this, 400), RelativeLayout.LayoutParams.MATCH_PARENT));
                    slidingDrawer.setLayoutParams(layoutParams);
                }
                break;
            //在线人数点击
            case R.id.tv_onlinePeople:
                initonlinePeopleandtaolun();
                tv_onlinePeople.setBackgroundResource(R.color.homepage_titlefont);
                tv_onlinePeople.setTextColor(0xFFffffff);
                recyclerView.setAdapter(meberAdapter);
                meberAdapter.notifyDataSetChanged();
                GetImMemberList();
                searchView.setVisibility(View.VISIBLE);
                layout_edtext.setVisibility(View.GONE);
                break;
            //讨论点击
            case R.id.radio_taolun:
                initonlinePeopleandtaolun();
                rb_taolun.setBackgroundResource(R.color.homepage_titlefont);
                rb_taolun.setTextColor(0xFFffffff);
                recyclerView.setAdapter(messageAdapter);
                messageAdapter.notifyDataSetChanged();
                searchView.setVisibility(View.GONE);
                layout_edtext.setVisibility(View.VISIBLE);
                break;
            //发送消息
            case R.id.bt_send:
                SendImMessage(ed_text_message.getText().toString());
                break;
            //话筒
            case R.id.tv_mike:
                sendType = "话筒";
                Logger.i("Logger","话筒："+sessionId);
                if(AVChatManager.getInstance().isAudienceRole()){
                    tv_mike.setChecked(false);
                    tv_mike.setTextColor(0xFFa9a9a9);
                    toast("正在向老师请求话筒发言，请求发言中....等待老师授权");
                    MsgHelper.getInstance().sendP2PCustomNotification(sessionId,MeetingOptCommand.SPEAK_REQUEST.getValue(),TeacherId,null);
                }else {
                    tv_mike.setChecked(true);
                    tv_mike.setTextColor(0xFF12B9A0);
                    toast("老师已授权！");
                }
                break;
            //举手
            case R.id.tv_raisehands:
                sendType = "举手";
                Logger.i("Logger","举手："+TeacherId);
                if(AVChatManager.getInstance().isAudienceRole()){
                    tv_raisehands.setChecked(false);
                    tv_raisehands.setTextColor(0xFFa9a9a9);
                    toast("正在向老师请求举手，举手中....等待老师授权");
                    MsgHelper.getInstance().sendP2PCustomNotification(sessionId,MeetingOptCommand.SPEAK_REQUEST.getValue(),TeacherId,null);
                }else {
                    tv_raisehands.setChecked(true);
                    tv_raisehands.setTextColor(0xFF12B9A0);
                    //TODO 开启白板权限
                    doodleView.setEnableView(true);
                    tv_clear.setEnabled(true);
                    toast("老师已授权！");
                }
                break;
            //笔记
            case R.id.tv_notebook:
               // hideAlltext();
                tv_notebook.setChecked(true);
                tv_notebook.setTextColor(0xFF12B9A0);
                //1.直接启动
                //1.直接启动
//                startActivity(new Intent(this, ScreenShotActivity.class));
                //2.通过service启动
              //  startService(new Intent(this, ScreenShotService.class));
                requestCapturePermission();
//                SPUtils.screenShotWholeScreen(LiveBroadcastActivity.this);
//                iv_meitupian.setImageBitmap(SPUtils.screenShotWholeScreen(LiveBroadcastActivity.this));
                break;
            //截屏
            case R.id.tv_screenshot:
                mMediaProjectionManager = (MediaProjectionManager) getApplication().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
                if (Build.VERSION.SDK_INT >= 21) {
                    startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), 1);

                } else {
                    Log.e("TAG", "版本过低,无法截屏");
                }
                break;
            //画笔
            case R.id.tv_paint:
                new LiveSelectPenPopWindow(LiveBroadcastActivity.this,doodleView).showAsDropDown(tv_notebook);
                        //showAtBottom(tv_paint);
//                doodleView.setPaintSize(3);
//                doodleView.setPaintType(ActionTypeEnum.Path.getValue());
                break;
            //橡皮
            case R.id.tv_rubber:
//                doodleView.setPaintColor(R.color.appstyletitlecolor);
//                doodleView.setPaintSize(30);
                doodleView.paintBack();
                break;
            //清空
            case R.id.tv_clear:
                doodleView.clear();
                break;

        }
    }
    private void hideAlltext(){
        tv_mike.setChecked(false);
        tv_raisehands.setChecked(false);
//        tv_notebook.setChecked(false);
        tv_mike.setTextColor(0xFFa9a9a9);
        tv_raisehands.setTextColor(0xFFa9a9a9);
//        tv_notebook.setTextColor(0xFFa9a9a9);
    }
    public void requestCapturePermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            //5.0 之后才允许使用屏幕截图
            return;
        }
        MediaProjectionManager mediaProjectionManager = (MediaProjectionManager)
                getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        startActivityForResult(
                mediaProjectionManager.createScreenCaptureIntent(),
                1111);
    }
    /**
     * ***************************** 画板 ***********************************
     */
    private void initDoodleView(String account) {
        //      toast("init doodle success");
        // add support ActionType
        SupportActionType.getInstance().addSupportActionType(ActionTypeEnum.Path.getValue(), MyPath.class);
        //判断是否为创建房间房主
//        if (account.equals(SPUtils.getInstance(this).getInt("student_id")+"")) {
//            doodleView.init(sessionId, account, DoodleView.Mode.BOTH, Color.WHITE, Color.BLACK, this, this);
//        } else {
        doodleView.init(sessionId, account, DoodleView.Mode.BOTH, Color.WHITE, Color.BLUE, this, this);
        //       }

        doodleView.setPaintSize(3);
        doodleView.setPaintType(ActionTypeEnum.Path.getValue());
        doodleView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    //允许ScrollView截断点击事件，ScrollView可滑动
                    slidingDrawer.requestDisallowInterceptTouchEvent(false);
                } else {
                    //不允许ScrollView截断点击事件，点击事件由子View处理
                    slidingDrawer.requestDisallowInterceptTouchEvent(true);
                }
                return false;
            }
        });
        doodleView.setEnableView(false);
        // adjust paint offset
        new Handler(getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                Rect frame = new Rect();
                getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
                int statusBarHeight = frame.top;
                int statusBarWidth = frame.left;
                Log.i("Doodle", "statusBarHeight =" + statusBarHeight);

                int marginTop = doodleView.getTop();
                Log.i("Doodle", "doodleView marginTop =" + marginTop);

                int marginLeft = doodleView.getLeft();
                Log.i("Doodle", "doodleView marginLeft =" + marginLeft);

                float offsetX = statusBarWidth;
                float offsetY = statusBarHeight + marginTop;
                //statusBarHeight + c + DensityUtil.dp2pxInt(220) + DensityUtil.dp2pxInt(40);

                doodleView.setPaintOffset(offsetX, offsetY);
                Log.i("Doodle", "client1 offsetX = " + offsetX + ", offsetY = " + offsetY);
            }
        }, 50);
    }
    @Override
    public void onFlipPage(Transaction transaction) {
        pageFlip(transaction);
    }
    private DMData docData;
    private Transaction docTransaction;
    private void pageFlip(final Transaction transaction) {
        this.docTransaction = transaction;
        if (transaction == null) {
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showLoadDialog();
            }
        });

        // 文档第0页，表示退出文档分享
        if (transaction.getCurrentPageNum() == 0) {
            isFileMode = false;
            hideLoadDialog();
            return;
        }
        // 如果文档信息已经下载过了，就不用载了。直接去载翻页图片
        isFileMode = true;

        if (docData != null && docData.getDocId().equals(transaction.getDocId())) {
            doDownloadPage(document, transaction.getCurrentPageNum());
            return;
        }
        LogUtil.i(TAG, "doc id:" + transaction.getDocId());
        DocumentManager.getInstance().querySingleDocumentData(transaction.getDocId(), new RequestCallback<DMData>() {
            @Override
            public void onSuccess(DMData dmData) {
                LogUtil.i(TAG, "query doc success");
                docData = dmData;
                document = new Document(dmData, new HashMap<Integer, String>(), FileDownloadStatusEnum.NotDownload);
                doDownloadPage(document, transaction.getCurrentPageNum());
            }

            @Override
            public void onFailed(int i) {
                LogUtil.i(TAG, "query doc failed, code:" + i);
                showLoadDialog();
            }

            @Override
            public void onException(Throwable throwable) {
                LogUtil.i(TAG, "query doc exception:" + throwable.toString());
            }
        });
    }
    private void doDownloadPage(final Document document, final int currentPage) {
        if (document == null || document.getDmData() == null) {
            return;
        }

        final String path = StorageUtil.getWritePath(document.getDmData().getDocName() + currentPage, StorageType.TYPE_FILE);
        String url = document.getDmData().getTransCodedUrl(currentPage, DMDocTransQuality.MEDIUM);
        Map<Integer, String> pathMap = document.getPathMap();
        pathMap.put(currentPage, path);
        document.setPathMap(pathMap);
        NIMClient.getService(NosService.class).download(url, null, path).setCallback(new RequestCallback() {
            @Override
            public void onSuccess(Object o) {
                hideLoadDialog();
                Bitmap bitmap = BitmapFactory.decodeFile(path);
                LogUtil.i(TAG, "Audience download success, set bitmap:" + bitmap);
                doodleView.setImageView(bitmap);
            }

            @Override
            public void onFailed(int i) {
                LogUtil.i(TAG, "Audience download file failed, code:" + i);
                //showRetryLoadingText();
            }

            @Override
            public void onException(Throwable throwable) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1111:
                if (resultCode == RESULT_OK && data != null) {
                    FloatWindowsService.setResultData(data);
                    startService(new Intent(getApplicationContext(), FloatWindowsService.class));
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(2000);
                                if(StringUtils.isNull(SPUtils.getInstance(context).getString("LiveBijiImg"))){return;}
                                QiniuUploadUtils.getInstance().uploadFile(SPUtils.getInstance(context).getString("LiveBijiImg"), new QiniuUploadUtils.UploadListener() {
                                    @Override
                                    public void onUploadSuccess(String key) {
                                        hideLoadDialog();
                                        String yuming = SPUtils.getInstance(LiveBroadcastActivity.this).getString("domain");
                                        final String mimage = yuming+key;
                                        Map<String,String> map = new HashMap<>();
                                        map.put("category_id",SPUtils.getInstance(context).getInt("havenoteId")+"");
                                        map.put("title","课堂直播笔记");
                                        String smimage = "<img src=\"" + mimage + "\"/>";
                                        map.put("content",smimage);
                                        post("note/addNote",map,BaseBean.class,false);
                                    }
                                    @Override
                                    public void onUploadFail(Error error) {
                                    }
                                },SPUtils.getInstance(LiveBroadcastActivity.this).getString("uptoken"));
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

                }
                break;
        }
        if (requestCode == 1 && data != null) {
            parseData(data);
        }
    }
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void parseData(Intent data) {
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        final int width = dm.widthPixels;         // 屏幕宽度（像素）
        final int height = dm.heightPixels;

        MediaProjection mMediaProjection = mMediaProjectionManager.getMediaProjection(Activity.RESULT_OK, data);
        ImageReader mImageReader = ImageReader.newInstance(
                width,
                height,
                PixelFormat.RGBA_8888, 1);
        VirtualDisplay mVirtualDisplay = mMediaProjection.createVirtualDisplay("screen-mirror",
                width,
                height,
                Resources.getSystem().getDisplayMetrics().densityDpi,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mImageReader.getSurface(), null, null);

        Image image = mImageReader.acquireLatestImage();
        // TODO 将image保存到本地即可
        if (image != null) {
            Image.Plane[] planes = image.getPlanes();
            if (planes.length > 0) {
                final ByteBuffer buffer = planes[0].getBuffer();
                int pixelStride = planes[0].getPixelStride();
                int rowStride = planes[0].getRowStride();
                int rowPadding = rowStride - pixelStride * width;

                // create bitmap
                Bitmap bmp = Bitmap.createBitmap(width + rowPadding / pixelStride, height,
                        Bitmap.Config.ARGB_8888);
                bmp.copyPixelsFromBuffer(buffer);

                Bitmap croppedBitmap = Bitmap.createBitmap(bmp, 0, 0, width, height);
                // 获取内置SD卡路径
                String sdCardPath = Environment.getExternalStorageDirectory().getPath();
                // 图片文件路径
                String filePath = sdCardPath + File.separator + "Myscreenshot" + String.valueOf(DateUtils.getStringToDate(DateUtils.getCurrentDate())) + ".jpg";
                File file = new File(filePath);
                try {
                    FileOutputStream os = new FileOutputStream(file);
                    croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                    os.flush();
                    os.close();
                    toast("截屏完成,存储完成");
                    //Log.d("a7888", "存储完成");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (croppedBitmap != null) {
                    croppedBitmap.recycle();
                }
                if (bmp != null) {
                    bmp.recycle();
                }
            }
        }
        // Log.d("a7888", "存储完成");
        mVirtualDisplay.release();
        mVirtualDisplay = null;
    }
    //---------------接收多人白板数据观察者------------
    Observer<RTSTunData> receiveDataObserver = new Observer<RTSTunData>() {
        @Override
        public void onEvent(RTSTunData rtsTunData) {
            String data = "[parse bytes error]";
            try {
                data = new String(rtsTunData.getData(), 0, rtsTunData.getLength(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            TransactionCenter.getInstance().onReceive(sessionId, "", data);
        }
    };
    //--------监听互动白板通道状态------------
    RTSChannelStateObserver channelStateObserver = new RTSChannelStateObserver() {

        @Override
        public void onConnectResult(String localSessionId, RTSTunnelType tunType, long channelId, int code, String recordFile) {
            // 与服务器连接结果通知，成功返回 200, 同时返回服务器录制文件的地址
//            Toast.makeText(LiveBroadcastActivity.this, "onConnectResult, tunType=" + tunType.toString() +
//                    ", channelId=" + channelId +
//                    ", code=" + code, Toast.LENGTH_SHORT).show();
            if (code != 200) {
                RTSManager2.getInstance().leaveSession(sessionId, null);
                return;
            }

            // 主播进入，
            // 1、第一次进入，或者异常退出发送白板清空指令。
            // 2、网络变化，发送主播的同步数据。
            List<Transaction> cache = new ArrayList<>(1);
            // roomInfo.getCreator().equals(DemoCache.getAccount())
            if (false) {
                if (isFirstComing) {
                    isFirstComing = false;
                    cache.add(new Transaction().makeClearSelfTransaction());
                    cache.add(new Transaction().makeFlipTranscation("", 0, 0, 1));
                    TransactionCenter.getInstance().sendToRemote(sessionId, null, cache);
                } else {
                    TransactionCenter.getInstance().onNetWorkChange(sessionId, true);
                }
            } else {
                // 非主播进入房间，发送同步请求，请求主播向他同步之前的白板笔记
               // Toast.makeText(LiveBroadcastActivity.this, "send sync request", Toast.LENGTH_SHORT).show();
                TransactionCenter.getInstance().onNetWorkChange(sessionId, false);
                cache.add(new Transaction().makeSyncRequestTransaction());
                TransactionCenter.getInstance().sendToRemote(sessionId, "", cache);
            }
        }

        @Override
        public void onChannelEstablished(String localSessionId, RTSTunnelType tunType) {
            // 双方通道连接建立(对方用户已加入)
           // toast("对方用户已加入");
        }

        @Override
        public void onUserJoin(String localSessionId, RTSTunnelType tunType, String account) {
            // 用户加入
            if(!SPUtils.getInstance(context).getString("accid").equals(account)){
              //  toast("用户加入");
            }

        }

        @Override
        public void onUserLeave(String localSessionId, RTSTunnelType tunType, String account, int event) {
            // 用户离开
            if(!SPUtils.getInstance(context).getString("accid").equals(account)){
               // toast("用户离开");
            }

        }

        @Override
        public void onDisconnectServer(String localSessionId, RTSTunnelType tunType) {
            // 与服务器断开连接
        }

        @Override
        public void onError(String localSessionId, RTSTunnelType tunType, int error) {
            // 通道发生错误
        }

        @Override
        public void onNetworkStatusChange(String localSessionId, RTSTunnelType channelType, int value) {
            // 网络信号强弱
        }
    };
    //-------------监听多人互动白板控制回调---------------
    Observer<RTSControlEvent> controlObserver = new Observer<RTSControlEvent>() {
        @Override
        public void onEvent(RTSControlEvent rtsControlEvent) {
            //  your codes
            toast("指令内容---" + rtsControlEvent.getExtra());
        }
    };
    //--------------监听音视频会话信息--------
    AVChatStateObserverLite register = new AVChatStateObserverLite() {
        @Override
        public void onJoinedChannel(int i, String s, String s1, int i1) {

        }

        @Override
        public void onUserJoined(String s) {
            if(s.equals(TeacherId)){
                toast("老师进入课堂直播间");
            }
            for (ChatRoomMemberBean.mlist mlist : alllist_meber) {
                if(mlist.accid.equals(s)){
                    mlist.chatRoomMember = new ChatRoomMember();
                }
            }
            meberAdapter.notifyDataSetChanged();
//            GetImMemberList();
        }

        @Override
        public void onUserLeave(String s, int i) {
            if(s.equals(TeacherId)){
                toast("老师退出课堂直播间");
                //TODO 关闭锁屏
                setSuoPing = false;
                tv_suoping.setVisibility(View.GONE);
                //TODO 关闭音视频权限
                AVChatManager.getInstance().enableAudienceRole(true);
                tv_mike.setChecked(false);
                tv_mike.setTextColor(0xFFa9a9a9);
                tv_raisehands.setChecked(false);
                tv_raisehands.setTextColor(0xFFa9a9a9);
                //TODO 关闭白板权限
                doodleView.setEnableView(false);
                tv_clear.setEnabled(false);
            }
            for (ChatRoomMemberBean.mlist mlist : alllist_meber) {
                if(mlist.accid.equals(s)){
                    mlist.chatRoomMember = null;
                }
            }
            meberAdapter.notifyDataSetChanged();
//            GetImMemberList();
        }

        @Override
        public void onLeaveChannel() {

        }

        @Override
        public void onProtocolIncompatible(int i) {

        }

        @Override
        public void onDisconnectServer(int i) {

        }

        @Override
        public void onNetworkQuality(String s, int i, AVChatNetworkStats avChatNetworkStats) {

        }

        @Override
        public void onCallEstablished() {

        }

        @Override
        public void onDeviceEvent(int i, String s) {

        }

        @Override
        public void onConnectionTypeChanged(int i) {

        }

        @Override
        public void onFirstVideoFrameAvailable(String s) {

        }

        @Override
        public void onFirstVideoFrameRendered(String s) {

        }

        @Override
        public void onVideoFrameResolutionChanged(String s, int i, int i1, int i2) {

        }

        @Override
        public void onVideoFpsReported(String s, int i) {

        }

        @Override
        public boolean onVideoFrameFilter(AVChatVideoFrame avChatVideoFrame, boolean b) {
            return false;
        }

        @Override
        public boolean onAudioFrameFilter(AVChatAudioFrame avChatAudioFrame) {
            return false;
        }

        @Override
        public void onAudioDeviceChanged(int i) {

        }

        @Override
        public void onReportSpeaker(Map<String, Integer> map, int i) {

        }

        @Override
        public void onSessionStats(AVChatSessionStats avChatSessionStats) {

        }

        @Override
        public void onLiveEvent(int i) {

        }
    };
    //------------------


    @Override
    protected void onDestroy() {
        super.onDestroy();
        onleave(sessionId);
        leaveAvRoom();
        NIMClient.getService(ChatRoomService.class).exitChatRoom(sessionId);
    }

    /**
     * 加入聊天室
     */
    private void JoinImRoom(){
        // roomId 表示聊天室ID
        EnterChatRoomData data = new EnterChatRoomData(sessionId);
        data.setNick(SPUtils.getInstance(context).getString("name"));
        data.setAvatar(SPUtils.getInstance(context).getString("head_image"));
        // 以登录一次不重试为例
        NIMClient.getService(ChatRoomService.class).enterChatRoomEx(data, 1).setCallback(new RequestCallback<EnterChatRoomResultData>() {
            @Override
            public void onSuccess(EnterChatRoomResultData result) {
                result.getMember().setNick(SPUtils.getInstance(context).getString("name"));
                if(StringUtils.isNull(result.getRoomInfo().getAnnouncement())){return;}
                if(result.getRoomInfo().getAnnouncement().equals("lock_screen")){
                    setSuoPing = true;
                    tv_suoping.setVisibility(View.VISIBLE);
                }
               // toast("加入聊天室成功");
                // 登录成功
                //SendImMessage("加入聊天室成功");
            }
            @Override
            public void onFailed(int code) {
                // 登录失败
            }
            @Override
            public void onException(Throwable exception) {
                // 错误
            }
        });
    }
    /**
     * 发送聊天室消息
     */
    private void SendImMessage(String text){
        // 示例用roomId
        String roomId = sessionId;
        // 文本消息内容
       // String text = "这是聊天室文本消息";
        // 创建聊天室文本消息
//        Map map = new HashMap();
//        map.put("name",""+SPUtils.getInstance(context).getString("name")+":");
//        map.put("content",""+text);
//        String content  = SPUtils.toJson(false,map);
        final ChatRoomMessage message = ChatRoomMessageBuilder.createChatRoomTextMessage(roomId, text);
        Map<String,Object> map1 = new HashMap<>();
        map1.put("name",""+SPUtils.getInstance(context).getString("name"));
        map1.put("avatar",""+SPUtils.getInstance(context).getString("head_image"));
        message.setRemoteExtension(map1);
        // 配置不存历史记录
        CustomChatRoomMessageConfig config = new CustomChatRoomMessageConfig();
        config.skipHistory = false;
        message.setChatRoomConfig(config);
//        MemberPushOption memberPushOption= new MemberPushOption();
//        memberPushOption.setForcePushContent(SPUtils.getInstance(context).getString("name"));
//        message.setMemberPushOption(memberPushOption);
        //message.setC
       // message.setPushContent(SPUtils.getInstance(context).getString("name"));
       // message.setLocalExtension();
       // message.setFromAccount(SPUtils.getInstance(context).getString("name"));
        // 将文本消息发送出去
        NIMClient.getService(ChatRoomService.class).sendMessage(message, false)
                .setCallback(new RequestCallback<Void>() {
                    @Override
                    public void onSuccess(Void param) {
                       // toast("发送消息成功");
                        ed_text_message.setText("");
                        list_message.add(message);
                        messageAdapter.notifyDataSetChanged();
                        // 成功
                    }
                    @Override
                    public void onFailed(int code) {
                        if(code ==  13004 || code == 13006){
                            Logger.i("code---->",code+"");
                            ed_text_message.setText("");
                            toast("已被老师禁言");
                        }

                        // 失败
                    }
                    @Override
                    public void onException(Throwable exception) {
                        // 错误
                    }
                });
    }
    private List<ChatRoomMember> mresult = new ArrayList<>();
    /**
     * 获取聊天室在线成员
     */
    private int i_online=0;
    private void GetImMemberList(){
        mresult.clear();
        i_online=0;
//        for(int j =0;j<alllist_meber.size();j++){
//            alllist_meber.get(j).chatRoomMember = null;
//        }
        // 以游客为例，从最新时间开始，查询10条
        NIMClient.getService(ChatRoomService.class).fetchRoomMembers(sessionId, MemberQueryType.GUEST, 0, 100).setCallback(new RequestCallbackWrapper<List<ChatRoomMember>>() {
            @Override
            public void onResult(int code, List<ChatRoomMember> result, Throwable exception) {
                if(result==null){return;}
                mresult.addAll(result);
                for(int j =0;j<alllist_meber.size();j++){
                    for(int i = 0;i<result.size();i++){
                        if(alllist_meber.get(j).accid .equals(result.get(i).getAccount()) ){
                            alllist_meber.get(j).chatRoomMember = result.get(i);
                            i_online++;
                        }
                    }
                }
                Collections.sort(alllist_meber, new Comparator<ChatRoomMemberBean.mlist>() {
                    @Override
                    public int compare(ChatRoomMemberBean.mlist o1, ChatRoomMemberBean.mlist o2) {
                        ChatRoomMember lastchatRoomMember  = o1.chatRoomMember;
                        ChatRoomMember nextchatRoomMember = o2.chatRoomMember;
                        if(lastchatRoomMember == null && nextchatRoomMember ==null){
                            return 0;
                        }else if(lastchatRoomMember == null && nextchatRoomMember !=null){
                            return 1;
                        }else if(lastchatRoomMember != null && nextchatRoomMember ==null){
                            return -1;
                        }
                        else {
                            if(o1.accid .equals(TeacherId)){
                                return -1;
                            }else {
                                return 1;
                            }
                        }
                    }
                });
                tv_onlinePeople.setText("在线人数︵"+i_online+"︶");
                tv_all_onlinepeople.setText(i_online+"/"+allOnline);
                meberAdapter.notifyDataSetChanged();
            }
        });
        NIMClient.getService(ChatRoomService.class).fetchRoomMembers(sessionId, MemberQueryType.ONLINE_NORMAL, 0, 100).setCallback(new RequestCallbackWrapper<List<ChatRoomMember>>() {
            @Override
            public void onResult(int code, List<ChatRoomMember> result, Throwable exception) {
                if(result==null){return;}
                mresult.addAll(result);

                for(int j =0;j<alllist_meber.size();j++){
                    for(int i = 0;i<result.size();i++){
                        if(alllist_meber.get(j).accid .equals(result.get(i).getAccount()) ){
                            alllist_meber.get(j).chatRoomMember = result.get(i);
                            i_online++;
                        }
                    }
                }
                Collections.sort(alllist_meber, new Comparator<ChatRoomMemberBean.mlist>() {
                    @Override
                    public int compare(ChatRoomMemberBean.mlist o1, ChatRoomMemberBean.mlist o2) {
                       ChatRoomMember lastchatRoomMember  = o1.chatRoomMember;
                       ChatRoomMember nextchatRoomMember = o2.chatRoomMember;
                       if(lastchatRoomMember == null && nextchatRoomMember ==null){
                           return 0;
                       }else if(lastchatRoomMember == null && nextchatRoomMember !=null){
                           return 1;
                       }else if(lastchatRoomMember != null && nextchatRoomMember ==null){
                           return -1;
                       }else {
                           return 0;
                       }
                    }
                });
                tv_onlinePeople.setText("在线人数︵"+i_online+"︶");
                tv_all_onlinepeople.setText(i_online+"/"+allOnline);
                meberAdapter.notifyDataSetChanged();
            }
        });
    }
    /**
     * 接收聊天室消息
     */
    Observer<List<ChatRoomMessage>> incomingChatRoomMsg = new Observer<List<ChatRoomMessage>>() {
        @Override
        public void onEvent(List<ChatRoomMessage> messages) {
            //toast("接收消息成功");
            // 处理新收到的消息
            if (messages == null || messages.isEmpty()) {
                return;
            }

            for (IMMessage msg : messages) {
                if (msg == null) {
                    LogUtil.e(TAG, "receive chat room message null");
                    continue;
                }

                LogUtil.d(TAG, "receive msg type:" + msg.getMsgType());
                if (msg.getMsgType() == MsgTypeEnum.notification) {

                }


                Map<String,Object> map =  msg.getRemoteExtension();
                if(map != null) {
                    // Log.i("messages--->", map.toString());
                    if(map.get("lock_screen")!=null){
                        if((boolean)map.get("lock_screen")){
                            setSuoPing = true;
                            tv_suoping.setVisibility(View.VISIBLE);
                        }else {
                            setSuoPing = false;
                            tv_suoping.setVisibility(View.GONE);
                        }
                        return;
                    }
                }
                        //getSenderAvatar();
//                Log.i("messages--->", messages.get(0).getContent());
                for (ChatRoomMessage message : messages) {
                    if(StringUtils.isNull( message.getContent())){messages.remove(message);}
                }
                list_message.addAll(messages);
                messageAdapter.notifyDataSetChanged();
//                messages.get(0).getContent();
//                messages.get(0).getFromAccount();
                // 成员权限
//                if (sendReceiveMemPermissions(msg)) {
//                    return;
//                }
//
//                for (RoomMsgObserver observer : roomMsgObservers) {
//                    observer.onMsgIncoming(messages);
//                }
            }
        }

    };
    Observer<CustomNotification> customNotification = new Observer<CustomNotification>() {
        @Override
        public void onEvent(CustomNotification customNotification) {
            String fromAccount = customNotification.getFromAccount();
            String content = customNotification.getContent();
            int command = 0;
            List<String> accounts = new ArrayList<>();
            String roomId = null;
            try {
                JsonObject json = new JsonParser().parse(content).getAsJsonObject();
                int id = json.get("type").getAsInt();
                if (id == 10) {
                    // 聊天室通知
                    JsonObject data = json.get("data").getAsJsonObject();
                    roomId = data.get("room_id").getAsString();
                    command = data.get("command").getAsInt();
//                    JsonArray array = json.get("uids").getAsJsonArray();
//                    for (int i = 0; i < array.size(); i++) {

//                        accounts.add(array.get(i).toString());
//                    }

                }
                Logger.i(TAG, "receive custom notification, command:" + command);

            } catch (Exception e) {
                return;
            }
            //主持人同意连麦请求
            if (command == MeetingOptCommand.SPEAK_ACCEPT.getValue()) {
                if(sendType.equals("话筒")){
                    //离开观众身份
                    AVChatManager.getInstance().enableAudienceRole(false);
                    toast("老师同意你的发言");
                    tv_mike.setChecked(true);
                    tv_mike.setTextColor(0xFF12B9A0);
                }else {
                    //离开观众身份
                    AVChatManager.getInstance().enableAudienceRole(false);
                    toast("老师同意你的举手");
                    tv_raisehands.setChecked(true);
                    tv_raisehands.setTextColor(0xFF12B9A0);
                    //TODO 开启白板权限
                    doodleView.setEnableView(true);
                    tv_clear.setEnabled(true);
                }


            }
            //主持人拒绝或关闭连麦
            else if (command == MeetingOptCommand.SPEAK_REJECT.getValue()) {
                if(sendType.equals("话筒")){
                    //加入观众身份
                    AVChatManager.getInstance().enableAudienceRole(true);
                    tv_mike.setChecked(false);
                    tv_mike.setTextColor(0xFFa9a9a9);
                    toast("老师关闭了你的话筒发言");
                    //TODO 关闭白板权限
                    doodleView.setEnableView(false);
                    tv_clear.setEnabled(false);
                }else {
                    //加入观众身份
                    AVChatManager.getInstance().enableAudienceRole(true);
                    tv_raisehands.setChecked(false);
                    tv_raisehands.setTextColor(0xFFa9a9a9);
                    toast("老师拒绝了你的举手");
                    //TODO 关闭白板权限
                    doodleView.setEnableView(false);
                    tv_clear.setEnabled(false);
                }
                hideAlltext();
                MsgHelper.getInstance().sendP2PCustomNotification(sessionId,MeetingOptCommand.SPEAK_RESPONSE_CANCEL.getValue(),TeacherId,null);
            }else if(command == MeetingOptCommand.SPEAK_REJECT_LIMIT.getValue()){
                toast("已有2人举手，请稍后再试!");
            }
            //主持人通知有权限的成员列表
            else if (command == MeetingOptCommand.ALL_STATUS.getValue()) {

            }
            //有权限的成员向请求者返回自己有权限的通知
            else if (command == MeetingOptCommand.STATUS_RESPONSE.getValue()) {

            }
        }

    } ;
    Observer<AVChatControlEvent> callControlObserver = new Observer<AVChatControlEvent>() {
        @Override
        public void onEvent(AVChatControlEvent netCallControlNotification) {
            handleCallControl(netCallControlNotification);
        }
    };
    private void handleCallControl(AVChatControlEvent event) {
        switch (event.getControlCommand()) {
            case SWITCH_AUDIO_TO_VIDEO:
                // 对方请求切换音频到视频
                break;
            case SWITCH_AUDIO_TO_VIDEO_AGREE:
                // 对方同意切换音频到视频
                // 切换操作
                // 打开视频
                AVChatManager.getInstance().enableVideo();
                AVChatManager.getInstance().startVideoPreview();
                // 是否在发送视频 即摄像头是否开启
                if (AVChatManager.getInstance().isLocalVideoMuted()) {
                    AVChatManager.getInstance().muteLocalVideo(false);

                }
                break;
            case SWITCH_AUDIO_TO_VIDEO_REJECT:
                // 对方拒绝切换音频到视频
                break;
            case SWITCH_VIDEO_TO_AUDIO:
                // 对方请求视频切换到音频
                //关闭视频
                AVChatManager.getInstance().stopVideoPreview();
                AVChatManager.getInstance().disableVideo();
                break;
            case NOTIFY_VIDEO_OFF:
                // 对方关闭视频的通知
                break;
            case NOTIFY_VIDEO_ON:
                // 对方开启视频的通知
                break;
            default:
                break;
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume");
        if (player != null) {
            player.onActivityResume(true);
        }
    }
    @Override
    public void onBackPressed() {
        Log.i(TAG, "onBackPressed");
        if(setSuoPing){
            toast("锁屏中，无法返回退出");
            return;
        }
        mBackPressed = true;
        finish();
        super.onBackPressed();
    }
}
